package logic

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"demo/internal/errorx"
	"demo/internal/svc"
	"demo/internal/types"
	"demo/model"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/core/stores/redis"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

type QuestionUpdateLogic struct {
	logx.Logger
	ctx    context.Context
	rds *redis.Redis
	svcCtx *svc.ServiceContext
	modelQ model.QuestionModel
}

func NewQuestionUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QuestionUpdateLogic {
	rds, err := redis.NewRedis(redis.RedisConf{
		Host: svcCtx.Config.Redis.Host,
		Pass: svcCtx.Config.Redis.Pass,
		Type: svcCtx.Config.Redis.Type,
	})
	if err != nil {
		logx.Errorf("redis init error: %v", err)
	}
	return &QuestionUpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		rds: rds,
		svcCtx: svcCtx,
		modelQ: model.NewQuestionModel(svcCtx.Orm),
	}
}

func (l *QuestionUpdateLogic) QuestionUpdate(req *types.QuestionUpdateRequest) (resp *types.CommonResponse, err error) {
	// todo: add your logic here and delete this line
	qst,err := l.modelQ.FindOne(l.ctx,nil,req.Id)
	if err != nil {
		return nil,errorx.NewBizError(500,"数据库查询错误")
	}
	// 删除redis中可能存在的数据
	l.rds.DelCtx(l.ctx,QuestionDetailPrefix + strconv.FormatInt(req.Id,10))
	err = l.modelQ.Trans(l.ctx,func(context context.Context, session sqlx.Session) error {
		if qst.QstSort != 0 && qst.QstSort != req.QstSort {

			// step1 查询nowId（现在需要跟的节点ID）之前跟的节点，使节点qst_sort为id（此节点ID）
			twoQst,err := l.modelQ.FindOneByQstSort(context,session,req.QstSort)
			if err != sqlx.ErrNotFound && twoQst != nil {
				twoQst.QstSort = req.Id
				l.modelQ.Update(context,session,twoQst)
			}else if err == sqlx.ErrNotFound {
				return errorx.NewBizError(500,"父节点未查询到，请重新输入")
			}
			// step2 查询之前跟在此节点的节点，使其qst_sort为preId（之前此节点跟的节点ID）
			oneQst,err := l.modelQ.FindOneByQstSort(context,session,qst.Id)
			if err != sqlx.ErrNotFound && oneQst != nil {
				oneQst.QstSort = qst.QstSort
				l.modelQ.Update(context,session,oneQst)
			}
			
			qst.QstSort = req.QstSort
		}
		if len(strings.TrimSpace(req.QstContent)) > 0 && qst.QstContent != req.QstContent {
			fmt.Println("问题内容是：",req.QstContent)
			qst.QstContent = req.QstContent
		}
		if req.IsMustAnswer != nil && *req.IsMustAnswer != qst.IsMustAnswer{
			qst.IsMustAnswer = *req.IsMustAnswer
		}
		if req.IsShow != nil && *req.IsShow != qst.IsShow{
			qst.IsShow = *req.IsShow
		}
		err = l.modelQ.Update(context,session,qst)
		return err
	})

	if err != nil {
		return nil,err
	}

	return &types.CommonResponse{
		Code: 200,
		Msg: "更新成功",
	},nil
}
